<template>
  <ElDialog v-model="visible" title="资源选择器" width="900px" top="5vh">
    <!-- 资源类型Tab -->
    <div class="flex">
      <ElTabs v-model="activeTab" class="demo-tabs">
        <ElTabPane v-for="tab in tabs" :key="tab.value" :label="tab.label" :name="tab.value" />
      </ElTabs>
      <!-- 搜索框 -->
      <div class="resource-toolbar">
        <ElInput v-model="search" placeholder="搜索此分类下的资源" class="wim" clearable />
        <ElButton type="primary" @click="onSearch">搜索</ElButton>
        <ElButton type="success" @click="onUploadClick">上传</ElButton>
        <input ref="uploadRef" type="file" class="nond" @change="handleFileChange" />
      </div>
    </div>

    <!-- 资源网格 -->
    <div class="resource-grid">
      <div
        v-for="item in filteredList"
        :key="item.url"
        class="resource-item"
        :class="{ selected: isSelected(item.urls) }"
        @click="select(item.urls)"
      >
        <img v-if="item.type === 'image' && item.url" :src="item.url" @error="handleImageError" />
        <div v-else-if="!item.url" class="file-icon">?</div>
        <div v-else class="file-icon">{{ item.ext }}</div>
        <div class="file-name" :title="item.name">{{ item.name }}</div>
      </div>
    </div>
    <!-- 分页 -->
    <div class="resource-footer">
      <ElPagination
        v-model:current-page="page"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
      />
      <div class="resource-actions">
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton type="primary" :disabled="!canConfirm" @click="confirm">确认</ElButton>
      </div>
    </div>
  </ElDialog>
</template>
<script setup>
  import { ref, computed, watch, onMounted, nextTick } from 'vue'
  import { ElDialog, ElButton, ElMessage, ElInput, ElPagination } from 'element-plus'
  import { fetchResourceList, uploadResource, fetchResourceTypes } from '@/api/common'
  import { getFullImageUrl } from '@/utils/image'

  const props = defineProps({
    visible: Boolean,
    multiple: { type: Boolean, default: false } // 是否支持多选，默认false（单选）
  })
  const emit = defineEmits(['update:visible', 'select'])

  const visible = ref(props.visible)
  watch(
    () => props.visible,
    (v) => {
      visible.value = v
      // 对话框打开时重置选中状态
      if (v) {
        selectedUrl.value = ''
        selectedUrls.value = []
      }
    }
  )
  watch(visible, (v) => emit('update:visible', v))

  // 资源类型Tab（由后端返回）
  const tabs = ref([])
  const activeTab = ref('')
  onMounted(async () => {
    //// console.log('AvatarPickerDialog mounted')
    try {
      const res = await fetchResourceTypes()
      // // console.log('fetchResourceTypes result:', res)
      tabs.value = res.map((item) => ({
        label: item.name,
        value: String(item.id)
      }))
      await nextTick()
      activeTab.value = tabs.value.length ? tabs.value[0].value : ''
      // // console.log('tabs:', tabs.value, 'activeTab:', activeTab.value)
      // 首次tab赋值后，立即请求带type的资源列表
      if (activeTab.value) {
        getResourceList()
      }
    } catch {
      ElMessage.error('资源类型加载失败')
      // // console.error('fetchResourceTypes error:', e)
    }
  })

  // 搜索
  const search = ref('')

  // 资源数据
  const resourceList = ref([])
  const page = ref(1)
  const pageSize = ref(20)
  const total = ref(0)
  const loading = ref(false)

  // 选中（单选模式用字符串，多选模式用数组）
  const selectedUrl = ref('')
  const selectedUrls = ref([])

  // 获取资源接口
  const getResourceList = async () => {
    loading.value = true
    try {
      const res = await fetchResourceList({
        type: activeTab.value,
        search: search.value,
        page: page.value,
        pageSize: pageSize.value
      })
      // 使用工具方法拼接完整的图片 URL
      resourceList.value = (res.data || [])
        .filter((item) => item.url || item.urls) // 过滤掉没有 URL 的项
        .map((item) => ({
          url: getFullImageUrl(item.url || item.urls), // 拼接完整URL用于显示
          urls: item.urls || item.url || '', // 保持原始相对路径
          name: item.file_name || '未命名',
          type: 'image', // 可根据 extension 判断类型
          ext: item.extension || 'img'
        }))
      total.value = res.total || 0
    } catch {
      ElMessage.error('资源加载失败')
      // console.error('fetchResourceList error:', e)
    }
    loading.value = false
  }

  // 监听tab、分页变化自动请求
  let isFirstTabLoad = true
  watch([activeTab, page], () => {
    if (!activeTab.value) return
    // 首次tab赋值后已请求过一次，watch里跳过
    if (isFirstTabLoad) {
      isFirstTabLoad = false
      return
    }
    getResourceList()
  })
  // 搜索按钮点击
  const onSearch = () => {
    page.value = 1 // 搜索时重置页码
    getResourceList()
  }

  // 过滤显示
  const filteredList = computed(() => resourceList.value)

  // 判断图片是否被选中
  const isSelected = (urls) => {
    return props.multiple ? selectedUrls.value.includes(urls) : selectedUrl.value === urls
  }

  // 判断是否可以确认
  const canConfirm = computed(() => {
    return props.multiple ? selectedUrls.value.length > 0 : !!selectedUrl.value
  })

  // 选中
  const select = (urls) => {
    // console.log('选择图片:', { urls, multiple: props.multiple })

    if (props.multiple) {
      // 多选模式：切换选中状态
      const index = selectedUrls.value.indexOf(urls)
      if (index > -1) {
        selectedUrls.value.splice(index, 1)
        // console.log('取消选中，当前已选:', selectedUrls.value)
      } else {
        selectedUrls.value.push(urls)
        // console.log('添加选中，当前已选:', selectedUrls.value)
      }
    } else {
      // 单选模式：直接替换
      selectedUrl.value = urls
      // console.log('单选模式，已选:', selectedUrl.value)
    }
  }

  // 图片加载错误处理
  const handleImageError = () => {
    // const img = event.target
    // console.warn('图片加载失败:', img.src)
    // 可以设置一个默认的占位图
    // img.src = '/path/to/placeholder.png'
  }

  const confirm = () => {
    // console.log('确认选择:', {
    //   multiple: props.multiple,
    //   selectedUrl: selectedUrl.value,
    //   selectedUrls: selectedUrls.value
    // })
    // return
    if (props.multiple) {
      // 多选模式：返回所有选中的图片
      const items = resourceList.value.filter((i) => selectedUrls.value.includes(i.urls))
      // console.log('多选模式，找到的图片:', items)
      if (items.length > 0) {
        const result = items.map((item) => ({ fullUrl: item.urls, url: item.urls }))
        // console.log('发送选择结果:', result)
        emit('select', result)
      }
    } else {
      // 单选模式：返回单个图片
      const item = resourceList.value.find((i) => i.urls === selectedUrl.value)
      console.log('单选模式，找到的图片:', item)
      if (item) {
        const result = { fullUrl: item.urls, url: item.urls }
        console.log('发送选择结果:', result)
        emit('select', result)
      }
    }
    visible.value = false
  }

  // 上传
  const uploadRef = ref()

  const onUploadClick = () => {
    if (uploadRef.value) {
      uploadRef.value.click()
    }
  }

  const handleFileChange = async (event) => {
    const file = event.target.files[0]
    if (!file) return
    const formData = new FormData()
    formData.append('file', file)
    try {
      const res = await uploadResource(formData)
      const uploadedUrl = res.url || res.urls
      if (uploadedUrl) {
        resourceList.value.unshift({
          url: getFullImageUrl(uploadedUrl), // 拼接完整URL用于显示
          urls: res.urls || res.url || '', // 上传后补全 urls 字段
          name: file.name,
          type: 'image',
          ext: file.name.split('.').pop() || 'img'
        })
        ElMessage.success('上传成功')
      } else {
        ElMessage.error('上传失败：未返回图片URL')
        // console.error('uploadResource response:', res)
      }
    } catch {
      ElMessage.error('上传失败')
      // console.error('uploadResource error:', e)
    }
    event.target.value = '' // 清空文件选择
  }
</script>

<style scoped>
  @import './style.scss';
</style>
